package com.itheima.consumer.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.Map;

/**
 * Author:Cammy.Wu
 * Date:2024-05-27
 * Description:MQ事件监听
 */

@Slf4j
@Component
public class SpringRabbitListener {

    // 利用RabbitListener来声明要监听的队列信息
    // 将来一旦监听的队列中有了消息，就会推送给当前服务，调用当前方法，处理消息。
    // 可以看到方法体中接收的就是消息体的内容

    @RabbitListener(queues = "simple.queue")
    public void listenerSimpleQueue(Message message) {
        log.info("监听到simple.queue的消息：【{}】", message.getMessageProperties().getMessageId());
        log.info("监听到simple.queue的消息：【{}】", new String(message.getBody()));
//        throw new RuntimeException("我是故意的！");
    }

    @RabbitListener(queues = "work.queue")
    public void listenerWorkQueue1(String message) throws InterruptedException {
        log.info("消费者1——监听到 work.queue 的消息：【{}】", message);
        System.out.println("消费者1——监听到 work.queue 的消息:" + message + "," + LocalTime.now());
        Thread.sleep(25);
    }

    @RabbitListener(queues = "work.queue")
    public void listenerWorkQueue2(String message) throws InterruptedException {
        System.err.println("消费者2——监听到 work.queue 的消息:" + message + "," + LocalTime.now());
        Thread.sleep(200);
    }

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg) {
        System.out.println("消费者1接收到Fanout消息：【" + msg + "】");
    }

    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg) {
        System.out.println("消费者2接收到Fanout消息：【" + msg + "】");
    }

    @RabbitListener(queues = "direct.queue1")
    public void listenDirectQueue1(String msg) {
        System.out.println("消费者1接收到direct.queue1的消息：【" + msg + "】");
    }

    @RabbitListener(queues = "direct.queue2")
    public void listenDirectQueue2(String msg) {
        System.out.println("消费者2接收到direct.queue2的消息：【" + msg + "】");
    }

    @RabbitListener(queues = "topic.queue1")
    public void listenTopicQueue1(String msg) {
        System.out.println("消费者1接收到topic.queue1的消息：【" + msg + "】");
    }

    @RabbitListener(queues = "topic.queue2")
    public void listenTopicQueue2(String msg) {
        System.out.println("消费者2接收到topic.queue2的消息：【" + msg + "】");
    }

    @RabbitListener(queues = "object.queue")
    public void listenSimpleQueueMessage(Map<String, Object> msg) {
        System.out.println("消费者接收到object.queue消息：【" + msg + "】");
    }
}
